//
//  ULNetHelper.m
//  Marry
//
//  Created by usera on 16/3/21.
//  Copyright © 2016年 usera. All rights reserved.
//

#import "ULNetHelper.h"

@interface ULNetHelper ()
@property (nonatomic,strong) AFHTTPSessionManager *manager;
@property (nonatomic,strong) NSURLSessionDownloadTask *downloadTask;
@end

@implementation ULNetHelper

//初始化请求管理器
+ (AFHTTPSessionManager *)getManager {
    //实例化管理器
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil ,nil];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    //请求超时时间
    manager.requestSerializer.timeoutInterval = 60.f;
    
    return manager;
}

//实例化
+ (ULNetHelper *)shared {
    static ULNetHelper *instance;
    @synchronized(self) {
        if (!instance) {
            instance = [[self alloc] init];
        }
        return instance;
    }
}

- (id)init {
    if(self =[super init]) {
        //初始化请求管理器
        self.manager = [ULNetHelper getManager];
        //添加状态栏活动指示器
        [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    }
    return self;
}

#pragma mark - 单例请求

//取消请求
+ (void)CancelAllOperations {
    [[ULNetHelper shared].manager.operationQueue cancelAllOperations];
}

//GET请求服务器JSON数据
+ (void)GET:(NSString *)url parameters:(NSDictionary *)dict success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    NSLog(@"GET-->%@?%@",url,[self stringWithParameters:dict]);
    [[ULNetHelper shared].manager GET:url
                           parameters:dict
                             progress:nil
                              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                  NSLog(@"请求成功-->%@",responseObject);
                                  //子线程的数据传给主线程
                                  dispatch_async(dispatch_get_main_queue(), ^{
                                      if (success) {
                                          success(responseObject);
                                      }
                                  });
                              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                  if([error code] == NSURLErrorCancelled) {//失败原因 是否请求被取消
                                      return;
                                  }else {
                                      if ([error code] == NSURLErrorNotConnectedToInternet) {
                                          NSLog(@"网络不可用");
                                      }else {
                                          NSLog(@"请求超时");
                                      }
                                  }
                                  NSLog(@"请求失败-->%@", error);
                                  //子线程的数据传给主线程
                                  dispatch_async(dispatch_get_main_queue(), ^{
                                      if (failure) {
                                          failure(error);
                                      }
                                  });
                              }];
}

//POST请求服务器JSON数据
+ (void)POST:(NSString *)url parameters:(NSDictionary *)dict success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    NSLog(@"POST-->%@?%@",url,[self stringWithParameters:dict]);
    [[ULNetHelper shared].manager POST:url
                            parameters:dict
                              progress:nil
                               success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                   NSLog(@"请求成功-->%@",responseObject);
                                   //子线程的数据传给主线程
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       if (success) {
                                           success(responseObject);
                                       }
                                   });
                               } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                   if([error code] == NSURLErrorCancelled) {//失败原因 是否请求被取消
                                       return;
                                   }else {
                                       if ([error code] == NSURLErrorNotConnectedToInternet) {
                                           NSLog(@"网络不可用");
                                       }else {
                                           NSLog(@"请求超时");
                                       }
                                   }
                                   NSLog(@"请求失败-->%@", error);
                                   //子线程的数据传给主线程
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       if (failure) {
                                           failure(error);
                                       }
                                   });
                               }];
}

#pragma mark - 直接请求

//GET请求服务器JSON数据
+ (void)GET:(NSString *)url parameters:(NSDictionary *)dict success:(void (^)(id responseObject))success {
    [ULNetHelper shared];
    NSLog(@"GET-->%@?%@",url,[self stringWithParameters:dict]);
    [[ULNetHelper getManager] GET:url
                       parameters:dict
                         progress:nil
                          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                              //NSLog(@"请求成功-->%@",responseObject);
                              //子线程的数据传给主线程
                              dispatch_async(dispatch_get_main_queue(), ^{
                                  if (success) {
                                      success(responseObject);
                                  }
                              });
                          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                              NSLog(@"请求失败-->%@", error);
                          }];
}

//POST请求服务器JSON数据
+ (void)POST:(NSString *)url parameters:(NSDictionary *)dict success:(void (^)(id responseObject))success {
    [ULNetHelper shared];
    NSLog(@"POST-->%@?%@",url,[self stringWithParameters:dict]);
    [[ULNetHelper getManager] POST:url
                        parameters:dict
                          progress:nil
                           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                               //NSLog(@"请求成功-->%@",responseObject);
                               //子线程的数据传给主线程
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (success) {
                                       success(responseObject);
                                   }
                               });
                           } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                               NSLog(@"请求失败-->%@", error);
                           }];
    
}


#pragma mark - 检查网络链接

//检查网络链接
+ (void)CheckConnectedSuccess:(void (^)(void))success failure:(void (^)(void))failure {
    //如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    //检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status == AFNetworkReachabilityStatusReachableViaWiFi){
            if (success) {
                success();
            }
            NSLog(@"WiFi");
        }
        else if(status == AFNetworkReachabilityStatusReachableViaWWAN){
            if (success) {
                success();
            }
            NSLog(@"3G");
        }
        else if(status == AFNetworkReachabilityStatusNotReachable){
            if (failure) {
                failure();
            }
            NSLog(@"无连接");
        }
        else if(status == AFNetworkReachabilityStatusUnknown){
            if (failure) {
                failure();
            }
            NSLog(@"未知网络");
        }
        else {
            if (failure) {
                failure();
            }
            NSLog(@"其他");
        }
        [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
    }];
}



/**
 *  字典键值拼接
 *  @param dict 需要拼接的字典
 *  @return 返回字符串
 */
+ (NSString*)stringWithParameters:(NSDictionary *)dict {
    NSMutableString *string = [[NSMutableString alloc] initWithString:@""];
    for (int i = 0; i < dict.count; i++) {
        [string appendFormat:@"%@=%@",dict.allKeys[i],dict.allValues[i]];
        if (i < dict.count-1) [string appendString:@"&"];
    }
    return string;
}

/**
 *  用正则表达式解析URL获取其中的参数
 *  @param CS  参数名
 *  @param URL 请求链接
 *  @return 参数
 */
+ (NSString *)jiexi:(NSString *)CS url:(NSString *)URL {
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",CS];
    NSRegularExpression *regex;
    regex = [NSRegularExpression regularExpressionWithPattern:regTags options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regex matchesInString:URL options:0 range:NSMakeRange(0, [URL length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [URL substringWithRange:[match rangeAtIndex:2]];
        //NSLog(@"分组2所对应的串:%@\n",tagValue);
        return tagValue;
    }
    return @"";
}


@end
